package pc

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
	"time"
)

//系统帐号的流水记录

//diamond为负数时表示减少,正数表示增加
func UpdateSystemUserDiamond(sysUid, diamond int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessCenter)
	sql := fmt.Sprintf(`
		UPDATE
			%v
		SET
			remain_diamond = remain_diamond + %v,
			cost_diamond = cost_diamond + %v,
			month_cost = month_cost + %v,
			week_cost = week_cost + %v,
			day_cost = day_cost + %v
		WHERE
			uid = %v
	`, TableSystemUser, diamond, -diamond, diamond, diamond, diamond, sysUid)
	result, err := o.Raw(sql).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//写系统帐号的钻石的流水
func NewSystemUserDiamondRecord(data map[string]interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessLog)
	//table := GetTodayMonthTable(TableSystemUserTran)
	table := TableSystemUserTran
	values, sql := InsertSql(table, data)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

//diamond为负数时表示减少,正数表示增加
func doSystemDiamond(sysUid, diamond, userUid, operateType, operateUid int64) error {
	o1 := NewDBOrm(DBChessCenter)
	o1.Begin()
	defer o1.Rollback()
	_, err := UpdateSystemUserDiamond(sysUid, diamond, o1)
	if err != nil {
		o1.Rollback()
		return err
	}

	o2 := NewDBOrm(DBChessLog)
	o2.Begin()
	defer o2.Rollback()
	data := map[string]interface{}{
		"sys_uid":      sysUid,
		"diamond":      diamond,
		"user_uid":     userUid,
		"operate_type": operateType,
		"operate_uid":  operateUid,
		"create_time":  time.Now().Unix(),
	}
	_, err = NewSystemUserDiamondRecord(data, o2)
	if err != nil {
		o1.Rollback()
		o2.Rollback()
		return err
	}
	o1.Commit()
	o2.Commit()
	return nil
}

//diamond为负数时表示减少,正数表示增加
func DoSystemDiamond(sysUid, diamond, userUid, operateType, operateUid, userType int64) error {
	err := doSystemDiamond(sysUid, diamond, userUid, operateType, operateUid)
	if err != nil {
		eventLog := map[string]interface{}{
			"module":     ModuleCard,
			"event_type": EventDelivery,
			"user_type":  userType,
			"uid":        userUid,
			"msg": fmt.Sprintf("从系统帐号:%v扣钻石数:%v到玩家或代理(ID:%v)失败,操作类型为:%v,失败日志:%v",
				sysUid, diamond, userUid, operateType, err),
		}
		go NewEventLog(eventLog)
		return err
	}
	return nil
}
